package com.example.demo.job;

import com.example.demo.course.Course;
import com.example.demo.course.repository.CourseRepository;
import com.example.demo.course.repository.UserCourseRepository;
import com.example.demo.util.EmailUtil;
import com.example.demo.util.TimeParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Component
public class ReminderJob {

    private static final Logger logger = LoggerFactory.getLogger(ReminderJob.class);

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private UserCourseRepository userCourseRepository;

    @Autowired
    private EmailUtil emailUtil;

    /**
     * 每5分钟执行一次的提醒检查
     * fixedRate单位：毫秒（5分钟=300000毫秒）
     */
    @Scheduled(fixedRate = 300000)
    public void checkUpcomingCourses() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime remindEnd = now.plusMinutes(30); // 30分钟内的课程

        logger.info("Reminder job started at: {}", now);

        // 1. 查询所有课程
        List<Course> allCourses = courseRepository.findAll();
        logger.info("Total courses found: {}", allCourses.size());

        // 2. 过滤出30分钟内开始的课程
        List<Course> coursesToRemind = new java.util.ArrayList<>();
        for (Course course : allCourses) {
            try {
                LocalDateTime startTime = TimeParser.parseCourseTime(course.getTime());
                if (startTime.isAfter(now) && startTime.isBefore(remindEnd)) {
                    coursesToRemind.add(course);
                    logger.info("Course to remind: {} at {}", course.getName(), startTime);
                }
            } catch (Exception e) {
                logger.error("Failed to parse course time for course: {}", course.getName(), e);
            }
        }

        logger.info("Courses to remind: {}", coursesToRemind.size());

        // 3. 为每门课程发送提醒
        coursesToRemind.forEach(course -> {
            List<String> studentEmails = userCourseRepository.findUserEmailsByCourseId(course.getId());
            logger.info("Sending reminders for course: {} to {} students", course.getName(), studentEmails.size());
            studentEmails.forEach(email -> {
                try {
                    emailUtil.sendReminder(email, course);
                    logger.info("Reminder sent to: {} for course: {}", email, course.getName());
                } catch (Exception e) {
                    logger.error("Failed to send reminder to: {} for course: {}", email, course.getName(), e);
                }
            });
        });

        logger.info("Reminder job completed at: {}", LocalDateTime.now());
    }
}